#!/usr/bin/env bash
. ./wvtest-bup.sh || exit $?
. ./dev/lib.sh || exit $?

set -o pipefail

top="$(WVPASS pwd)" || exit $?
tmpdir="$(WVPASS wvmktempdir)" || exit $?

export BUP_DIR="$tmpdir/bup"
export GIT_DIR="$tmpdir/bup"

bup() { "$top/bup" "$@"; }
compare-trees() { "$top/dev/compare-trees" "$@"; }

WVPASS bup init
WVPASS cd "$tmpdir"

WVSTART "index/save"
WVPASS mkdir src src/foo
WVPASS date > src/bar
WVPASS bup random 1k > src/baz
WVPASS bup on - index src
WVPASS bup on - save -ctn src src > get.log
WVPASSEQ $(WVPASS cat get.log | WVPASS wc -l) 2
tree_id=$(WVPASS awk 'FNR == 1' get.log) || exit $?
commit_id=$(WVPASS awk 'FNR == 2' get.log) || exit $?
WVPASS git ls-tree "$tree_id"
WVPASS git cat-file commit "$commit_id" | head -n 1 \
    | WVPASS grep "^tree $tree_id\$"

WVPASS bup restore -C restore "src/latest/$(pwd)/src/."
WVPASS compare-trees src/ restore/
WVPASS rm -r restore

WVSTART "split"
WVPASS bup on - split -ctn baz src/baz > get.log
tree_id=$(WVPASS awk 'FNR == 1' get.log) || exit $?
commit_id=$(WVPASS awk 'FNR == 2' get.log) || exit $?
WVPASS git ls-tree "$tree_id"
WVPASS git cat-file commit "$commit_id" | head -n 1 \
    | WVPASS grep "^tree $tree_id\$"
WVPASS bup join baz > restore-baz
WVPASS cmp src/baz restore-baz

repo_id="id--$(WVPASS git config --file "$tmpdir"/bup/config bup.repo.id)"

WVSTART "index-cache"
# there should be an index-cache now
for idx in "$tmpdir"/bup/objects/pack/*.idx ; do
    cachedidx="$HOME/.cache/bup/remote/$repo_id/$(basename "$idx")"
    WVPASS cmp "$idx" "$cachedidx"
done

WVSTART 'index-cache respects XDG_CACHE_DIR'
WVPASS mkdir xdg-cache
export XDG_CACHE_HOME="$(pwd)/xdg-cache"
WVPASS bup on - split -ct src/baz > /dev/null
# Ensure the cache is a subset of objects/pack
for idx in xdg-cache/bup/remote/"$repo_id"/*.idx ; do
    repo_idx="bup/objects/pack/$(basename "$idx")"
    WVPASS cmp "$idx" "$repo_idx"
done

WVSTART "suggest packs"
# we need to write a large object here, otherwise the
# buffering in the local connection on the client will
# kill the test - if everything is buffered then we get
# the index suggestions only at the end when we finish,
# not inbetween, and then don't exercise the suspend
# pack writing code path ...
WVPASS seq 100000 > "$tmpdir/longfile"
WVPASS bup on - split -ctn large "$tmpdir/longfile"
WVPASS rm -rf "$XDG_CACHE_HOME"/bup/remote/
WVPASS bup --debug on - split -ctn large "$tmpdir/longfile"
WVPASS test -f "$(ls "$XDG_CACHE_HOME"/bup/remote/*/*.idx | head -1)"

WVPASS cd "$top"
WVPASS rm -rf "$tmpdir"
